<?php
$this->AddHook('start_buildings', 'Transportation');

function Transportation($bot)
{
	if($bot->firstrun)
	{
		//not work if it's first bot cycle
		$Name = "Transportation"; $Version = "1.2"; $Date = "09.05.2012";
		$bot->ld->UpdatePluginVersion($bot, $Name, $Version, $Date )  ;
		return;
	}

	$data = $bot->ld->GetPlSettings("Transportation");
	if(!isset($data->echeck)) $data->echeck = "0";
	if(!isset($data->actionSubway)) $data->actionSubway = "0";
	if(!isset($data->supplyAfter)) $data->supplyAfter = "0";
	if(!isset($data->actionBus)) $data->actionBus = "0";
	
	$SubStop = NULL;
	$SubStopWorld = NULL;
	$SubStopInfo = NULL;
	$SubEntranceDowntown = array();
	$SubEntranceMain = array();
	$NoSubStop = false;
	$NoSubEntrance = false;
	$BusStopDowntown = array();
	$BusStopMain = array();
	$NoBusStop == false;
	
	if (isset($data->collectSubwayMainIN)) $SubEntranceMain = $data->collectSubwayMainIN;
	if (isset($data->collectBusMainIN)) $BusStopMain = $data->collectBusMainIN;
	if (isset($data->collectSubwayDTIN)) $SubEntranceDowntown = $data->collectSubwayDTIN;
	if (isset($data->collectBusDTIN)) $BusStopDowntown = $data->collectBusDTIN;

	if (isset($data->collectMainSubStop) && ($data->collectMainSubStop))
	{
		foreach($bot->fobjects as $obj)
		if ($obj["className"] == "SubwayReceiver")
		{
			$SubStop = $obj['id'];
			$SubStopWorld = "world_main";
		}
	}
	
	if (isset($data->collectDTSubStop) && ($data->collectDTSubStop))
	{
		foreach($bot->dt_fobjects as $obj)
		if ($obj["className"] == "SubwayReceiver")
		{
			$SubStop = $obj['id'];
			$SubStopWorld = "world_downtown";
		}
	}
	
	if(($data->actionSubway == "1") || ($data->actionBus == "1") || ($data->supplyAfter == "1"))
	{
		$msg = $bot->irc('u') . $bot->irc('b');
		$msg .= $bot->irc('cc') . '2';
		$msg .= $bot->irc('ff') . '13,5' . chr(232) . $bot->irc('ff') . '14,5';
		$msg .= 'Starting Plugin: Transportation';
		$bot->SendMsg($msg);

		$bot->SendMsg('=====================================');
		$bot->SendMsg('[Transportation] Action started...');

		// Find Entrances and Stop in Downlown.
/*		foreach($bot->dt_fobjects as $obj)
		{
			if ($obj["className"] == "BusStop")
			{
				$BusStopDowntown[] = $obj['id'];
				if($data->actionBus) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .')  in Downtown');
			}
			if ($obj["className"] == "Subway")
			{
				$SubEntranceDowntown[] = $obj['id'];
				if($data->actionSubway) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .')  in Downtown');
			}
			if ($obj["className"] == "SubwayReceiver")
			{
				$SubStop = $obj['id'];
				$SubStopWorld = "world_downtown";
				if($data->actionSubway) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .') in Downtown');
			}
		}
		// Find Entrances and Stop in Main World.
		foreach($bot->fobjects as $obj)
		{
			if ($obj["className"] == "BusStop")
			{
				$BusStopMain[] = $obj['id'];
				if($data->actionBus) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .')  in Main World');
			}
			if ($obj["className"] == "Subway")
			{
				$SubEntranceMain[] = $obj['id'];
				if($data->actionSubway) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .') in Main World');
			}
			if ($obj["className"] == "SubwayReceiver")
			{
				$SubStop = $obj['id'];
				$SubStopWorld = "world_main";
				if($data->actionSubway) $bot->SendMsg('[Transportation] Found '. $obj['itemName'] .' ('. $obj['id'] .') in Main World');
			}
		}
*/
		// ==================== Process Bus ====================
		// Check if at least 1 Bus Stop was found.
		if ((!count($BusStopMain)) && (!count($BusStopDowntown)))
		{
			$bot->SendMsg('[Transportation] No Bus Stops selected');
			$NoBusStop = true;
		}

		if(($data->actionBus == "1") && ($NoBusStop == false))
		{
			$repeattimes = 1;
			if((isset($data->rBusCollect) && ($data->rBusCollect == "1")) && (isset($data->rBusTimes) && ($data->rBusTimes > 0)))
			{
				$repeattimes = $data->rBusTimes;
			}

			//added LOOP for repeated collecting
			for($rtimes = 1; $rtimes <= $repeattimes; $rtimes++)
			{
				if($repeattimes > 1)
				{
					$bot->SendMsg('=====================================');
					$bot->SendMsg('[Transportation-Bus] LOOP #' . $rtimes . ' starting...');
				}

				// Send commuters then Bus to each Bus Stop in Main World.
				If (count($BusStopMain))
				{
					$bot->fobjects = $bot->LoadWorldObjects("world_main");
					foreach($BusStopMain as $id)
					{
						$obj = $bot->fobjects["w$id"];
						if($obj['mechanicData']['harvestState'] == NULL)
						{
							$obj['mechanicData']['harvestState'] = array();
							$obj['mechanicData']['harvestState']['customersReq'] = $bot->xmlsOb->GetBusStopCustomerCapacity($obj['itemName']);
							$obj['mechanicData']['harvestState']['customers'] = 0;
						}
						$NeededCustomers = $obj['mechanicData']['harvestState']['customersReq'] - $obj['mechanicData']['harvestState']['customers'];
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] .' ('. $obj['id'] .') : Sending '. $NeededCustomers .' Commuters...');
						for ($i = 0; $i < $NeededCustomers; $i++) $bot->NewObjectAction($obj, "harvestState", "NPCEnterAction", "process", "Bus");
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] .' ('. $obj['id'] .') : Sending Bus...');
						$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "BusStop");
					}
				}
				// Send commuters then Bus to each Bus Stop in Downtown.
				if (count($BusStopDowntown))
				{
					$bot->dt_fobjects = $bot->LoadWorldObjects("world_downtown");
					foreach($BusStopDowntown as $id)
					{
						$obj = $bot->dt_fobjects["w$id"];
						if($obj['mechanicData']['harvestState'] == NULL)
						{
							$obj['mechanicData']['harvestState'] = array();
							$obj['mechanicData']['harvestState']['customersReq'] = $bot->xmlsOb->GetBusStopCustomerCapacity($obj['itemName']);
							$obj['mechanicData']['harvestState']['customers'] = 0;
						}
						$NeededCustomers = $obj['mechanicData']['harvestState']['customersReq'] - $obj['mechanicData']['harvestState']['customers'];
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] .' ('. $obj['id'] .') : Sending '. $NeededCustomers .' Commuters...');
						for ($i = 0; $i < $NeededCustomers; $i++) $bot->NewObjectAction($obj, "harvestState", "NPCEnterAction", "process", "Bus");
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] .' ('. $obj['id'] .') : Sending Bus...');
						$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "BusStop");
					}
				}
			} // End Loop
		}
		
		// =================== Process Subway ==================
		// Check if Subway Stop was found.
		if ($SubStop == NULL)
		{
			$bot->SendMsg('[Transportation] Subway Stop not found');
			$NoSubStop == true;
		}
		// Check if at least 1 Subway Entrance was found.
		if ((!count($SubEntranceMain)) && (!count($SubEntranceDowntown)))
		{
			$bot->SendMsg('[Transportation] No Subway Entrances selected');
			$NoSubEntrance = true;
		}

		if(($data->actionSubway == "1") && ($NoSubStop == false) && ($NoSubEntrance == false))
		{
			$repeattimes = 1;
			if((isset($data->rSubCollect) && ($data->rSubCollect == "1")) && (isset($data->rSubTimes) && ($data->rSubTimes > 0)))
			{
				$repeattimes = $data->rBusTimes;
			}

			//added LOOP for repeated collecting
			for($rtimes = 1; $rtimes <= $repeattimes; $rtimes++)
			{
				if($repeattimes > 1)
				{
					$bot->SendMsg('=====================================');
					$bot->SendMsg('[Transportation-Subway] LOOP #' . $rtimes . ' starting...');
				}

				if(($bot->energy <= 0) && ($data->echeck == "1"))
					$bot->CheckEnergy();

				if($bot->energy > 0)
				{
					// Check if Subway Stop needs to be collected.
					$bot->ReloadConfig();
					$SubStopInfo = $bot->cfg->_value['data'][0]['data']['featureData']['subway'];
					if (is_array($SubStopInfo))
					{
						$times = count($SubStopInfo);
						if ($times)
						{
							$bot->LoadWorldObjects($SubStopWorld);
							if ($SubStopWorld == "world_main")
								$obj = $bot->fobjects["w$SubStop"];
							else
								$obj = $bot->dt_fobjects["w$SubStop"];

							$bot->SendMsg('[Transportation] '. $obj['itemName'] .' has '. $times .' subways to unload.');
							for ($loop = 1; $loop <= $times; $loop++)
							{
							$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Harvesting...');
							$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Subway Stop");
								if (isset($bot->error_msg))
								{
									$bot->ReloadConfig();
									if ($data->echeck=="1")
										$hasenergy = $bot->CheckEnergy();
									else
										$hasenergy = 0;
								
									if (($hasenergy == 0) && ($bot->Energy == 0))
										break;
								}
							}
						}
					}
					// Suppy (if needed), visit and collect Subway Entrances in Main World.
					If (count($SubEntranceMain))
					{
						$bot->fobjects = $bot->LoadWorldObjects("world_main");
						foreach($SubEntranceMain as $id)
						{
							$obj = $bot->fobjects["w$id"];
							if($obj["mechanicData"]["harvestState"] == NULL)
							{
								$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Supplying... (with goods)');
							$bot->NewObjectAction($obj, "supplyState", "GMPlay", "supply", "Subway");
								$obj["mechanicData"]["harvestState"] = array();
								$obj['mechanicData']['harvestState']['customersReq'] = 500;
								$obj['mechanicData']['harvestState']['customers'] = 0;
							}

							$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Sending visitors...');
							$bot->processVisits($obj);
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Harvesting...');
						$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "SubWay");
							if (isset($bot->error_msg))
							{
								$bot->ReloadConfig();
								if ($data->echeck=="1")
									$hasenergy = $bot->CheckEnergy();
								else
									$hasenergy = 0;
								
								if (($hasenergy == 0) && ($bot->Energy == 0))
									break;
							}
						}
					}
					// Suppy (if needed), visit and collect Subway Entrances in Downtown.
					if (count($SubEntranceDowntown))
					{
						$bot->dt_fobjects = $bot->LoadWorldObjects("world_downtown");
						foreach($SubEntranceDowntown as $id)
						{
							$obj = $bot->dt_fobjects["w$id"];
							if($obj["mechanicData"]["harvestState"] == NULL)
							{
								$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Supplying... (with goods)');
							$bot->NewObjectAction($obj, "supplyState", "GMPlay", "supply", "Subway");
								$obj["mechanicData"]["harvestState"] = array();
								$obj['mechanicData']['harvestState']['customersReq'] = 500;
								$obj['mechanicData']['harvestState']['customers'] = 0;
							}

							$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Sending visitors...');
							$bot->processVisits($obj);
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Harvesting...');
						$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "SubWay");
							if (isset($bot->error_msg))
							{
								$bot->ReloadConfig();
								if ($data->echeck=="1")
									$hasenergy = $bot->CheckEnergy();
								else
									$hasenergy = 0;

								if (($hasenergy == 0) && ($bot->Energy == 0))
									break;
							}
						}
					}
					// Collect from Subway Stop.
					$bot->ReloadConfig();
					$SubStopInfo = $bot->cfg->_value['data'][0]['data']['featureData']['subway'];
					if (is_array($SubStopInfo))
					{
						$times = count($SubStopInfo);
						if ($times)
						{
							$bot->LoadWorldObjects($SubStopWorld);
							if ($SubStopWorld == "world_main")
								$obj = $bot->fobjects["w$SubStop"];
							else
								$obj = $bot->dt_fobjects["w$SubStop"];

							for ($loop = 1; $loop <= $times; $loop++)
							{
							$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Harvesting...');
							$bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Subway Stop");
								if (isset($bot->error_msg))
								{
									$bot->ReloadConfig();
									if ($data->echeck=="1")
										$hasenergy = $bot->CheckEnergy();
									else
										$hasenergy = 0;
							
									if (($hasenergy == 0) && ($bot->Energy == 0))
										break;
								}
							}
						}
					}
				}
				else
				{
						$bot->SendMsg('[Transportation] No energy for Subways');
				}
			} // End Loop
		}
		// Supply Entrances After collecting from Subway Stop.
		if(($data->supplyAfter == "1") && ($NoSubStop == false) && ($NoSubEntrance == false))
		{
			// Suppy Entrances in Main World.
			if (count($SubEntranceMain))
			{
				$bot->fobjects = $bot->LoadWorldObjects("world_main");
				foreach($SubEntranceMain as $id)
				{
					$obj = $bot->fobjects["w$id"];
					if($obj["mechanicData"]["harvestState"] == NULL)
					{
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Supplying... (with goods)');
						$bot->NewObjectAction($obj, "supplyState", "GMPlay", "supply", "Subway");
					}
				}
			}
			// Suppy Entrances in Downtown
			if (count($SubEntranceDowntown))
			{
				$bot->dt_fobjects = $bot->LoadWorldObjects('world_downtown');
				foreach($SubEntranceDowntown as $id)
				{
					$obj = $bot->dt_fobjects["w$id"];
					if($obj["mechanicData"]["harvestState"] == NULL)
					{
						$bot->SendMsg('[Transportation] ' . $obj['itemName'] . ': Supplying... (with goods)');
						$bot->NewObjectAction($obj, "supplyState", "GMPlay", "supply", "Subway");
					}
				}
			}
		}
		$bot->SendMsg('[Transportation] Action done.');
	}
}

?>